/*
 * Alberto Ruiz-Larrea Guillén...11383
 * Erdi Dogruel..................14955
 * Marcos Pérez Martín...........10324
 */

package com.example.database;

import java.util.HashMap;
import java.util.Random;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.SystemClock;
import android.widget.TextView;

import com.example.androball_manager.FirstMenuActivity;

//This class simulates the match
public class UpdateTeams extends
		AsyncTask<String, Integer, HashMap<Integer, String>> {

	private OpenDB abrir;
	private int gameday;
	int result;
	TextView text;
	String str;
	HashMap<Integer, String> mapped;
	StringBuilder sb;
	private Handler customHandler = new Handler();
	long timeInMilliseconds = 0L;
	private long startTime = 0L;

	public UpdateTeams(OpenDB a, int gameday, String str, TextView text) {
		abrir = a;
		this.gameday = gameday;
		this.str = str;
		this.text = text;
	}

	@SuppressLint("UseValueOf")
	@Override
	protected HashMap<Integer, String> doInBackground(String... params) {

		HashMap<Integer, String> map = new HashMap<Integer, String>();
		int counter = 2;
		int add = 2;

		OpenDB db = abrir;
		SQLiteDatabase watch = db.getReadableDatabase();

		String[] columns = { OpenDB.id, OpenDB.game_home, OpenDB.game_away,
				OpenDB.score_home, OpenDB.score_away, OpenDB.gameday };

		String[] columns2 = { OpenDB.id, OpenDB.name, OpenDB.games_played,
				OpenDB.won_matches, OpenDB.draw_matches, OpenDB.lost_matches,
				OpenDB.score_home, OpenDB.score_away, OpenDB.points,
				OpenDB.rating };

		// actual gameday
		Cursor temp = watch.query(OpenDB.table3, columns, null, null, null,
				null, null);
		temp.moveToFirst();

		while (temp.getInt(3) != -1 && !temp.isAfterLast()) {
			temp.moveToNext();
		}
		this.gameday = temp.getInt(5);
		temp.close();

		// Cursor for selected team
		Cursor c_select = watch.query(OpenDB.table3, columns, OpenDB.gameday
				+ "=?" + " and " + " (" + OpenDB.game_home + "=?" + " or "
				+ OpenDB.game_away + "=?" + ")", new String[] {
				new Integer(this.gameday).toString(), str, str }, null, null,
				null);
		c_select.moveToFirst();

		// Table Gameday
		Cursor cursor = watch.query(OpenDB.table3, columns, OpenDB.gameday
				+ "=?", new String[] { new Integer(this.gameday).toString() },
				null, null, null);
		cursor.moveToFirst();

		SQLiteDatabase read = db.getWritableDatabase();
		ContentValues values_home = new ContentValues();
		ContentValues values_away = new ContentValues();
		ContentValues values_gameplan = new ContentValues();

		// scored goals
		map.put(counter, "Nextgame is:\n");
		counter = counter + add;
		map.put(counter,
				c_select.getString(1) + " vs. " + c_select.getString(2) + "\n");
		counter = counter + add;

		while (!cursor.isAfterLast() && !c_select.isAfterLast()) {

			boolean select_true = (str.equals(cursor.getString(1)) || str
					.equals(cursor.getString(2)));

			Cursor c_home = watch.query(OpenDB.table4, columns2, OpenDB.name
					+ "=?", new String[] { cursor.getString(1) }, null, null,
					null);
			c_home.moveToFirst();

			Cursor c_away = watch.query(OpenDB.table4, columns2, OpenDB.name
					+ "=?", new String[] { cursor.getString(2) }, null, null,
					null);
			c_away.moveToFirst();

			int score_home = 0;
			int score_away = 0;

			for (int i = 0; i < 10; i++) {

				Random hs = new Random();
				int t1 = c_home.getInt(9) + hs.nextInt(30);
				hs = new Random();
				int t2 = c_away.getInt(9) + hs.nextInt(20);
				hs = new Random();

				if (t1 > t2 && select_true) {
					map.put(counter, c_select.getString(1) + " attacks...\n");
					counter = counter + add;

				} else if (t1 < t2 && select_true) {
					map.put(counter, c_select.getString(2) + " attacks...\n");
					counter = counter + add;
				}

				int s = hs.nextInt(3);

				if (t1 > t2 && s == 1) {
					score_home++;
					if (select_true) {
						map.put(counter, "...and shots a Goal!!! " + score_home
								+ " : " + score_away + "\n");
						counter = counter + add;
					}

				} else if (t1 > t2 && s != 1) {
					if (select_true) {
						map.put(counter,
								"...attack is canceled by "
										+ c_select.getString(2) + "\n");
						counter = counter + add;
					}
				} else if (t1 < t2 && s == 1) {
					score_away++;
					if (select_true) {
						map.put(counter, "...and shots a Goal!!! " + score_home
								+ " : " + score_away + "\n");
						counter = counter + add;
					}

				} else if (t1 < t2 && s != 1) {
					if (select_true) {
						map.put(counter,
								"...attack is canceled by "
										+ c_select.getString(1) + "\n");
						counter = counter + add;
					}

				}
			}
			if (select_true) {
				map.put(counter, "\n" + "The Endscore is " + score_home + " : "
						+ score_away + "\n");
				counter = counter + add;
			}

			if (str == c_select.getString(1) && score_home > score_away
					&& select_true) {
				map.put(counter, str + " wins against " + c_select.getString(2)
						+ "\n");
				counter = counter + add;
			}

			else if (str == c_select.getString(1) && score_home < score_away
					&& select_true) {
				map.put(counter,
						str + " loses against " + c_select.getString(2) + "\n");
				counter = counter + add;
			}

			else if (str == c_select.getString(2) && score_home < score_away
					&& select_true) {
				map.put(counter, str + " wins against " + c_select.getString(2)
						+ "\n");
				counter = counter + add;
			}

			else if (str == c_select.getString(2) && score_home > score_away
					&& select_true) {
				map.put(counter,
						str + " loses against " + c_select.getString(2) + "\n");
				counter = counter + add;
			}

			values_gameplan.put(OpenDB.score_home, score_home);
			values_gameplan.put(OpenDB.score_away, score_away);

			read.update(OpenDB.table3, values_gameplan, OpenDB.game_home + "=?"
					+ " and " + OpenDB.game_away + "=?",
					new String[] { cursor.getString(1), cursor.getString(2) });

			int w = 0;
			int d = 0;
			int l = 0;
			int p = 0;
			int pa = 0;

			if (score_home > score_away) {
				w = 1;
				p = 3;

			}
			if (score_home == score_away) {
				d = 1;
				p = 1;
				pa = 1;
			}
			if (score_home < score_away) {
				l = 1;
				pa = 3;
			}

			values_home.put(OpenDB.games_played, c_home.getInt(2) + 1);
			values_home.put(OpenDB.won_matches, c_home.getInt(3) + w);
			values_home.put(OpenDB.draw_matches, c_home.getInt(4) + d);
			values_home.put(OpenDB.lost_matches, c_home.getInt(5) + l);
			values_home.put(OpenDB.score_home, c_home.getInt(6) + score_home);
			values_home.put(OpenDB.score_away, c_home.getInt(7) + score_away);
			values_home.put(OpenDB.points, c_home.getInt(8) + p);

			read.update(OpenDB.table4, values_home, OpenDB.name + "=?",
					new String[] { cursor.getString(1) });

			values_away.put(OpenDB.games_played, c_away.getInt(2) + 1);
			values_away.put(OpenDB.won_matches, c_away.getInt(3) + l);
			values_away.put(OpenDB.draw_matches, c_away.getInt(4) + d);
			values_away.put(OpenDB.lost_matches, c_away.getInt(5) + w);
			values_away.put(OpenDB.score_home, c_away.getInt(6) + score_away);
			values_away.put(OpenDB.score_away, c_away.getInt(7) + score_home);
			values_away.put(OpenDB.points, c_away.getInt(8) + pa);

			read.update(OpenDB.table4, values_away, OpenDB.name + "=?",
					new String[] { cursor.getString(2) });

			c_home.close();
			c_away.close();
			cursor.moveToNext();
		}
		cursor.close();
		c_select.close();

		return map;
	}

	@Override
	protected void onPostExecute(HashMap<Integer, String> result) {
		mapped = result;
		this.str = "";
		FirstMenuActivity.gameday = this.gameday;
		startTime = SystemClock.uptimeMillis();
		customHandler.postDelayed(updateTimerThread, 2000);
	}

	private Runnable updateTimerThread = new Runnable() {
		public void run() {
			timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
			int secs = (int) (timeInMilliseconds / 1000);
			if (mapped.get(secs) != null) {
				str = str + mapped.get(secs);
				text.setText(str);
			}
			customHandler.postDelayed(this, 2000);
		}

	};

}
